/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AltaAlquilerViewImpl.java
 *
 *
 */
package vista.alquiler;

import controlador.AlquilerController;
import controlador.ClienteController;
import controlador.ClienteControllerImpl;
import datechooser.model.multiple.Period;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.SystemColor;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import modelo.AlquilerModel;
import modelo.ClienteModel;
import modelo.ClienteModelImpl;
import modelo.PistaModel;
import modelo.PistaModelImpl;
import modelo.persistencia.hibernate.pojo.AlquilerImpl;
import modelo.persistencia.hibernate.pojo.PistaImpl;
import vista.AbstractViewImpl;
import vista.cliente.BusqDatosClienteImpl;
import vista.cliente.ClienteView;
import vista.informe.InformeVisualImpl;
import vista.pista.PistaTableAndComboModel;


/**
 *
 * @author juan
 */
public class AltaAlquilerViewImpl extends AbstractViewImpl<AlquilerController, AlquilerModel> implements AlquilerView {

    BusqDatosClienteImpl busq=null;

    PistaImpl pistaSeleccionada=null;

    boolean dnicorrecto=false;

    // para el combobox
    private PistaTableAndComboModel pistaComboModel;
    PistaModel pistaModel;

    public PistaModel getPistaModel() {
        return pistaModel;
    }

    public void setPistaModel(PistaModel pistaModel) {
        this.pistaModel = pistaModel;
    }
    ///--------------------

    /** Creates new form AltaAlquilerViewImpl */
    public AltaAlquilerViewImpl() {
        pistaComboModel = new PistaTableAndComboModel();
        this.setPistaModel(new PistaModelImpl());

        //panel interno para la busqueda de cliente
        busq=new BusqDatosClienteImpl();
        ClienteModel clienteModel = new ClienteModelImpl();
        List<ClienteView> clienteViews= new ArrayList<ClienteView>();
        clienteViews.add(busq);
        ClienteController clienteController = new ClienteControllerImpl();
        clienteController.setup(clienteModel, clienteViews);


        initComponents();

        this.refresh();



        this.jTabbedPane1.add("Busqueda de cliente", (JPanel)busq);
        //busq.display();


        



    }



    public void actualizarInforme(List<ArrayList> informe)
    {

        List<String> horas=informe.get(0);
        List<Boolean> disponibilidad=informe.get(1);

        JPanel borderlaoutpanel = new JPanel();
        this.jScrollPane1.setViewportView(borderlaoutpanel);
        borderlaoutpanel.setLayout(new BorderLayout(0, 0));

        JPanel columnpanel = new JPanel();
        borderlaoutpanel.add(columnpanel, BorderLayout.NORTH);
        columnpanel.setLayout(new GridLayout(0, 1, 0, 1));
        columnpanel.setBackground(Color.gray);


        for(int i=0;i<horas.size();i++)
        {
            JPanel rowPanel = new JPanel();
            rowPanel.setPreferredSize(new Dimension(300,43));
            columnpanel.add(rowPanel);
            rowPanel.setLayout(null);


            InformeVisualImpl button=new InformeVisualImpl(horas.get(i),disponibilidad.get(i));
            button.setBounds(20, 5, 109, 43);
            rowPanel.add(button);


            /*
            if(i%2==0)
                rowPanel.setBackground(SystemColor.inactiveCaptionBorder);
             */
        }




        JPanel panel = new JPanel();
        panel.add(new JButton()); //esto es solo un ejemplo de agregar un boton al JPAnel

        //aqui se agrega el JPanel al JScrollPane
        JScrollPane scroll = new JScrollPane(panel);

        //ahora agregamos el JScrollPane a la ventana
        this.jScrollPane1.add(scroll);
    }


    public void establecerFechasDisponibles() {
/*
        Period p;
        Calendar c;
        List<Period> lista = new ArrayList<Period>();


        for (Object hora : pistaSeleccionada.diasOcupados()) {
            Date d = (Date) hora;
            c= Calendar.getInstance();
            c.setTime(d);
            p = new Period(c);

            lista.add(p);

        }


        dateChooserCombo1.setForbidden(lista);
 * */
    }

    public void establecerHorasDisponibles(){

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm");
        String strFecha = dateChooserCombo1.getText()+" 00:00";
        Date fecha = null;
        try {

            fecha = sdf.parse(strFecha);

        } catch (ParseException ex) {

            ex.printStackTrace();

        }
        DefaultComboBoxModel model = new DefaultComboBoxModel();

        for(String s:pistaSeleccionada.horasLibres(fecha))
        {
            model.addElement(s);
        }

        listaHoras.setModel(model);
        listaHoras.updateUI();
        listaHoras.setEnabled(true);



        List<ArrayList> informe=pistaSeleccionada.getInformeHoras(fecha);
        actualizarInforme(informe);


    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtDNI = new javax.swing.JTextField();
        listaPistas = new javax.swing.JComboBox();
        listaHoras = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        dateChooserCombo1 = new datechooser.beans.DateChooserCombo();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();

        jLabel3.setText("Hora:");

        jLabel4.setText("Fecha:");

        jLabel1.setText("DNI:");

        jLabel2.setText("Pista:");

        listaPistas.setModel(pistaComboModel);
        listaPistas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listaPistasActionPerformed(evt);
            }
        });

        listaHoras.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00" }));
        listaHoras.setEnabled(false);
        listaHoras.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listaHorasActionPerformed(evt);
            }
        });

        jButton1.setText("Guardar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Buscar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        try {
            dateChooserCombo1.setDefaultPeriods(new datechooser.model.multiple.PeriodSet(new datechooser.model.multiple.Period(new java.util.GregorianCalendar(2012, 0, 10),
                new java.util.GregorianCalendar(2012, 0, 10))));
    } catch (datechooser.model.exeptions.IncompatibleDataExeption e1) {
        e1.printStackTrace();
    }
    dateChooserCombo1.addCommitListener(new datechooser.events.CommitListener() {
        public void onCommit(datechooser.events.CommitEvent evt) {
            dateChooserCombo1OnCommit(evt);
        }
    });
    dateChooserCombo1.addSelectionChangedListener(new datechooser.events.SelectionChangedListener() {
        public void onSelectionChange(datechooser.events.SelectionChangedEvent evt) {
            dateChooserCombo1OnSelectionChange(evt);
        }
    });

    jScrollPane1.setAutoscrolls(true);

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(58, 58, 58)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel2)
                        .addComponent(jLabel4)
                        .addComponent(jLabel1)
                        .addComponent(jLabel3))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(dateChooserCombo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(txtDNI, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButton2))
                        .addComponent(listaPistas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(listaHoras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(282, 282, 282)
                    .addComponent(jButton1)))
            .addGap(89, 89, 89)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 492, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(6, 6, 6)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 476, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                    .addGap(38, 38, 38)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(txtDNI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton2))
                    .addGap(28, 28, 28)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(listaPistas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(20, 20, 20)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel4)
                        .addComponent(dateChooserCombo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(38, 38, 38)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(listaHoras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(51, 51, 51)
                    .addComponent(jButton1))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)))
            .addContainerGap())
    );

    jPanel2.setBackground(java.awt.Color.white);

    jLabel5.setFont(new java.awt.Font("Lucida Grande", 1, 24));
    jLabel5.setText("Alta de alquiler");
    jLabel5.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(378, 378, 378)
            .addComponent(jLabel5)
            .addContainerGap(393, Short.MAX_VALUE))
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(17, 17, 17)
            .addComponent(jLabel5)
            .addContainerGap(31, Short.MAX_VALUE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(39, Short.MAX_VALUE))
    );
    }// </editor-fold>//GEN-END:initComponents

    private void listaHorasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listaHorasActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_listaHorasActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        if (dnicorrecto && listaPistas.getSelectedIndex() != -1 && !listaHoras.getSelectedItem().toString().equals("Ninguna")) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm");
            Date hora = null;
            try {
                hora = sdf.parse(dateChooserCombo1.getText() + " " + listaHoras.getSelectedItem().toString());
            } catch (ParseException ex) {
                Logger.getLogger(AltaAlquilerViewImpl.class.getName()).log(Level.SEVERE, null, ex);
            }

            List l = new ArrayList();
            l.add(null);//el id de alquiler se asigna automaticamente
            l.add(this.txtDNI.getText());
            l.add(pistaSeleccionada.getIdPista());
            l.add(hora);
            this.getController().nuevaEntidadGesture(l);
            JOptionPane.showMessageDialog(this, "Se ha realizado la reserva correctamente.");
        } else {
            JOptionPane.showMessageDialog(this, "Debe rellenar los datos correctamente antes de realizar la reserva.");

        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void listaPistasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listaPistasActionPerformed
      if (listaPistas.getSelectedIndex() != -1) { // si se ha seleccionado alguna fecha

            pistaSeleccionada = pistaComboModel.getPistas().get(listaPistas.getSelectedIndex());
            establecerFechasDisponibles();
            this.dateChooserCombo1.setEnabled(true);
            establecerHorasDisponibles();

        }else{

          dateChooserCombo1.setEnabled(false);
          listaHoras.setEnabled(false);

        }
    }//GEN-LAST:event_listaPistasActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

            //si no se encuentra el cliente se muestra mensaje
        if(!busq.buscar(txtDNI.getText())){
            JOptionPane.showMessageDialog(this, "Cliente no encontrado, tiene que darse de alta primero.");
            dnicorrecto=false;
            }else
                {
            dnicorrecto=true;
            }
        
    }//GEN-LAST:event_jButton2ActionPerformed

    private void dateChooserCombo1OnSelectionChange(datechooser.events.SelectionChangedEvent evt) {//GEN-FIRST:event_dateChooserCombo1OnSelectionChange

        

    }//GEN-LAST:event_dateChooserCombo1OnSelectionChange

    private void dateChooserCombo1OnCommit(datechooser.events.CommitEvent evt) {//GEN-FIRST:event_dateChooserCombo1OnCommit
        // TODO add your handling code here:
        establecerHorasDisponibles();
    }//GEN-LAST:event_dateChooserCombo1OnCommit

    @Override
    protected void refresh() {
        this.pistaComboModel.setPistas(getPistaModel().listar());
        if (listaPistas.getSelectedIndex() != -1)
            pistaSeleccionada = pistaComboModel.getPistas().get(listaPistas.getSelectedIndex());
        
        if(pistaSeleccionada!=null){
            establecerFechasDisponibles();
            establecerHorasDisponibles();
        }

    }

    protected PistaTableAndComboModel getComboModel() {
        return pistaComboModel;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private datechooser.beans.DateChooserCombo dateChooserCombo1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JComboBox listaHoras;
    private javax.swing.JComboBox listaPistas;
    private javax.swing.JTextField txtDNI;
    // End of variables declaration//GEN-END:variables

    public void gestionarAccion(AlquilerImpl a) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
